package com.liwy3.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * Copyright © 2022年10月20日 北京自如信息科技有限公司. All rights reserved.
 *
 * @Prject: liwy3
 * @Package: com.liwy3.thread
 * @Description:
 * @author: Crazy4J
 * @date: 2022年10月20日 21:00
 * @version: V1.0
 */
public class CompletableFutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> queryTask1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("执行1111");
            return "111";
        });

        CompletableFuture<String> queryTask2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("执行2222");
            return "222";
        });

        CompletableFuture<Void> allOf = CompletableFuture.allOf(queryTask1, queryTask2);
//        CompletableFuture<Object> anyOf = CompletableFuture.anyOf(queryTask1, queryTask2);
//
//        System.out.println(anyOf.get());


//        Thread.sleep(10000000000000L);
        long asyncStart = System.currentTimeMillis();
        execAsyncList();
        long asyncEnd = System.currentTimeMillis();


        long start = System.currentTimeMillis();
        execList();
        long end = System.currentTimeMillis();

        System.out.println("异步处理总耗时：" + (asyncEnd - asyncStart));
        System.out.println("同步处理总耗时：" + (end - start));

    }

    private static List<Integer> initList() {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            list.add(i);
        }
        return list;
    }

    public static void execAsyncList() {
        List<Integer> list = initList();
        List<CompletableFuture<Integer>> futureList = list.stream()
                .map(e -> CompletableFuture.supplyAsync(() -> exec(e))).collect(Collectors.toList());

        futureList.forEach(CompletableFuture::join);
    }

    public static void execList() {
        List<Integer> list = initList();
        list.forEach(CompletableFutureDemo::exec);
    }

    public static Integer exec(Integer e) {
        try {
            Thread.sleep(10);
            System.out.println(Thread.currentThread().getName() + "开始处理元素：" + e);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        return e;
    }

}
